class Solution {
public:
    int maxHeight(vector<vector<int>>& cuboids) {
        int n = cuboids.size();
        for(int i = 0;i < n;i++){
            sort(cuboids[i].begin(),cuboids[i].end());
        }
        sort(cuboids.begin(),cuboids.end(),[](auto& a,auto& b){
             if(a[2] == b[2] && a[1] == b[1]) return a[0] < b[0];
             if(a[2] == b[2]) return a[1] < b[1];
             return a[2] < b[2];
        });
        
        vector<int> dp(n);
        dp[0] = cuboids[0][2];
        int Max = dp[0];
        
        for(int i = 1;i < n;i++){
            Max = max(cuboids[i][2],Max);
            dp[i] = cuboids[i][2];
            for(int j = 0;j < i;j++){
                if(cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1]){
                    dp[i] = max(dp[i],dp[j]+cuboids[i][2]);
                    Max = max(Max,dp[i]);
                }
            }
        }
        return Max;
    }
};
